<!--
 * @Descripttion:
 * @version:
 * @Author: tanghao1
 * @Date: 2021-02-02 14:34:11
 * @LastEditors: tanghao1
 * @LastEditTime: 2021-04-27 15:49:43
-->
<template>
  <el-dialog
    ref="refDlg"
    :title="detailData===''? '上传图片' : '编辑图片'"
    :visible.sync="dialogShow"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :hide-func-bar="true"
    :before-close="clearForm"
    width="600px"
    @close="closeDialog"
  >
    <div>
      <el-form ref="form" :model="formData" :rules="formRules" size="mini" label-width="100px">
        <el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="图册:" prop="atlasName" :rules="atlasName">
                <!-- 一级图册 -->
                <el-col :span="8">
                  <el-select
                    v-model="formData.atlasName"
                    size="mini"
                    placeholder="请选择"
                    @blur="selectedOne"
                    @change="hadleSelectChange"
                  >
                    <el-option
                      v-for="item in atlasoneList"
                      :key="item.id"
                      :label="item.atlasName"
                      :value="item.id"
                    />
                  </el-select>
                </el-col>
                <!-- 二级图册 -->
                <el-col :span="8">
                  <el-select
                    v-model="formData.atlasNametwo"
                    size="mini"
                    placeholder="请选择"
                    :rules="gotoType"
                    @change="hadleSelectChangetwo"
                  >
                    <el-option
                      v-for="item in atlastwoList"
                      :key="item.id"
                      :label="item.atlasName"
                      :value="item.id"
                    />
                  </el-select>
                </el-col>
                <!-- 三级图册 -->
                <el-col :span="8">
                  <el-select
                    v-model="formData.atlasNamethree"
                    size="mini"
                    placeholder="请选择"
                    :rules="gotoType"
                    @change="hadleSelectChangethree"
                  >
                    <el-option
                      v-for="item in atlasthreeList"
                      :key="item.id"
                      :label="item.atlasName"
                      :value="item.id"
                    />
                  </el-select>
                </el-col>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 新增展示内容 -->
          <div v-if="detailData === ''">
            <el-col>
              <el-upload
                ref="upload"
                class="upload-demo"
                :headers="headers"
                :action="picUrl"
                :on-change="handleChange"
                :auto-upload="false"
                :show-file-list="false"
                :on-progress="handleProgress"
                multiple
              >
                <el-button slot="trigger" size="small" type="primary">浏览</el-button>
                <el-button style="margin-left: 10px;" size="small" type="primary" @click="clearUpload">清空上传</el-button>
              </el-upload>
            </el-col>
            <el-col>
              <el-table
                :data="tableData"
                style="width: 100%"
              >
                <el-table-column
                  prop="name"
                  label="图片名称"
                />
                <el-table-column
                  prop="size"
                  label="文件大小"
                />
                <el-table-column
                  label="上传进度"
                  width="100"
                >
                  <template v-slot="{row,$index}">
                    <el-progress :percentage="step" />
                  </template>
                </el-table-column>
                <el-table-column
                  prop="state"
                  label="上传状态"
                />
                <el-table-column
                  fixed="right"
                  label="操作"
                  width="100"
                >
                  <template v-slot="{row,$index}">
                    <el-button type="text" size="small" @click="handleDetail($index)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </div>
          <!-- 编辑展示内容 -->
          <div v-if="detailData !== ''">
            <el-row>
              <el-col :span="12">
                <el-form-item label="图片名称:" prop="fileName" :rules="fileName">
                  <el-input v-model.trim="formData.fileName" size="mini" placeholder="请输入图片名称" />
                </el-form-item>
              </el-col>

            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="图片" prop="smallUrl" :rules="smallUrl">
                  <!-- <el-upload
                  class="avatar-uploader"
                  :headers="headers"
                  :action="picUrl"
                  :show-file-list="false"
                  :auto-upload="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                > -->
                  <!-- <img v-if="imageUrl" :src="imageUrl" class="avatar" :preview-src-list="imagebigUrl">
                <i v-else class="el-icon-plus avatar-uploader-icon" /> -->
                  <el-image
                    style="width: 100px; height: 100px"
                    :src="imageUrl"
                    :preview-src-list="imagebigUrl"
                  />
                <!-- <el-button type="text" @click="downloadPic">下载</el-button> -->
                <!-- </el-upload> -->
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="锚点" prop="anchorPoint" :rules="anchorPoint">
                  <el-switch
                    v-model="formData.anchorPoint"
                  />
                </el-form-item>
              </el-col>
              <el-col v-show="formData.anchorPoint == 1" :span="12">
                <el-form-item label="锚点名称" prop="anchorPointName" :rules="anchorPointName">
                  <el-input v-model="formData.anchorPointName" size="mini" placeholder="请输入锚点名称" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="目录" prop="catalog" :rules="catalog">
                  <el-switch
                    v-model="formData.catalog"
                  />
                </el-form-item>
              </el-col>
              <el-col v-show="formData.catalog == 1" :span="12">
                <el-form-item label="目录名称" prop="catalogName" :rules="catalogName">
                  <el-input v-model="formData.catalogName" size="mini" placeholder="请输入目录名称" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-row>
      </el-form>
    </div>
    <div slot="footer">
      <el-button size="mini" @click="closeDialog">取消</el-button>
      <el-button v-if="detailData === ''" size="mini" type="primary" @click="upFile">开始上传</el-button>
      <el-button v-else size="mini" type="primary" @click="save">保存</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { getToken } from '@/utils/auth'
import { searchAtlas } from '@/api/shopauxPlat/atlasManagement'
import { saveAtlaspic, editAtlaspic } from '@/api/shopauxPlat/atlaspicManagement'
export default {
  name: 'DemoEditForm',
  props: {
    visible: {
      type: Boolean,
      default: false,
      required: true
    },
    detailData: {
      type: [String, Object],
      default: ''
    }
  },
  data() {
    return {
      picUrl: `${process.env.VUE_APP_BASE_API}/api/v1/file/upload`,
      headers: {
        'X-Token': this.$store.getters.token ? getToken() : '',
        'Authorization': this.$store.getters.token ? 'Bearer ' + getToken() : ''
      },
      submiting: false,
      pricingTypeCodeList: [], // 因子类型
      step: 0,
      atlasData: [],
      formData: {
        atlasName: '',
        atlasNametwo: '',
        atlasNamethree: '',
        state: true,
        fileName: '',
        anchorPoint: true,
        anchorPointName: '',
        atlasDetailName: '',
        catalog: '',
        catalogName: '',
        detailData: []
      },
      editData: {
      },
      formRules: {
        atlasName: [{
          required: true,
          message: '请输入图册名称',
          trigger: 'blur'
        }],
        state: [{
          required: true,
          message: '请选择是否显示',
          trigger: 'blur'
        }],
        uplodaFile: [{
          required: true,
          message: '请上传图片',
          trigger: 'blur'
        }],
        fileName: [{
          required: true,
          message: '请输入图片名称',
          trigger: 'blur'
        }],
        smallUrl: [{
          required: true,
          message: '请输入图片名称',
          trigger: 'blur'
        }],
        anchorPoint: [{
          required: true,
          message: '请选择锚点',
          trigger: 'blur'
        }],
        catalog: [{
          required: true,
          message: '请选择目录',
          trigger: 'blur'
        }],
        anchorPointName: [{
          required: true,
          message: '请输入锚点名称',
          trigger: 'blur'
        }],
        catalogName: [{
          required: true,
          message: '请输入目录名称',
          trigger: 'blur'
        }]
      },
      tableData: [],
      atlasoneList: [], // 一级图册
      atlastwoList: [], // 二级图册
      atlasthreeList: [] // 三级图册
    }
  },
  computed: {
    dialogShow: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  watch: {
    'formData.atlasName': {
      handler(val, oldVal) {
        for (let i = 0; i < this.atlasData.length; i++) {
          if (val === this.atlasData[i].atlasName) {
            this.atlastwoList = this.atlasData[i].next
          }
        }
        if (val !== oldVal && oldVal) {
          this.formData.atlasNametwo = ''
          this.formData.atlasNamethree = ''
        }
      },
      deep: true
    },
    'formData.atlasNametwo': {
      handler(val, oldVal) {
        for (let i = 0; i < this.atlastwoList.length; i++) {
          if (val === this.atlastwoList[i].atlasName) {
            this.atlasthreeList = this.atlastwoList[i].next
          }
        }
        if (val !== oldVal && oldVal) {
          this.formData.atlasNamethree = ''
        }
      },
      deep: true
    }
  },
  created() {
    const data = this.detailData
    if (data) {
      this.formData = Object.assign({}, data)
      if (this.formData.anchorPoint === 1) {
        this.formData.anchorPoint = true
      }
      if (this.formData.catalog === 1) {
        this.formData.catalog = true
      }
    }
    this.imageUrl = this.formData.smallUrl
    this.imagebigUrl = [this.formData.bigUrl]
    // 获取图册数据
    this.searchPage()
  },
  mounted() {

  },
  methods: {
    handleChange(event, file, fileList) {
      const isJPG = event.raw.type.split('/')[1]
      const isLt2M = event.size / 1024 / 1024 < 5
      const allowPic = ['jpg', 'png', 'jpeg']
      if (!allowPic.includes(isJPG)) {
        this.$message.error('上传图片只能是 png/jpg 格式!')
        return
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 5MB!')
        return
      }
      if (event && event.status === 'ready') {
        this.step = 0
        const data = {}
        data.name = event.name
        data.size = Math.ceil(event.size / 1024) + 'KB'
        data.state = '准备上传'
        data.raw = event.raw
        this.tableData.push(data)
      }
      if (event && event.status === 'success') {
        this.tableData.forEach(item => { item.state = '上传成功' })
        this.step = 100
      }
    },
    handleProgress(event, file, fileList) {

    },
    handleRemove(file, fileList) {

    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    closeDialog() {
      this.dialogShow = false
    },
    // 上传图片
    upFile() {
      if (!this.formData.atlasNamethree) {
        this.$message.error('请先选择图册')
        return
      }
      if (this.tableData.length === 0) {
        this.$message.warning('至少上传一张图片')
        return
      }
      const formData = new FormData()
      for (var i = 0; i < this.tableData.length; i++) {
        formData.append('files', this.tableData[i].raw)
      }
      formData.append('atlasId', this.formData.atlasNamethree)
      saveAtlaspic(formData).then(res => {
        if (res.success === 1) {
          this.$message.success('上传成功')
          this.dialogShow = false
          this.$emit('refreshTable')
        }
      })
      // this.$refs.upload.submit()
    },
    // 下载到本地
    // downloadPic() {
    //   const alink = document.createElement('a')
    //   alink.href = this.imageUrl
    //   alink.download = 'pic' // 图片名
    //   alink.click()
    // },
    // 编辑保存
    save() {
      const data = {}
      if (this.formData.anchorPoint) {
        if (this.formData.anchorPointName === '') {
          this.$message.warning('锚点名称必填!')
          return
        }
      }
      if (this.formData.catalog) {
        if (this.formData.catalogName === '') {
          this.$message.warning('目录名称必填!')
          return
        }
      }
      if (this.formData.anchorPoint) {
        data.anchorPoint = 1
      } else {
        data.anchorPoint = 0
      }
      data.anchorPointName = this.formData.anchorPointName
      this.atlasthreeList.forEach(item => {
        console.log(item)
        console.log(this.formData.atlasNamethree)
        if (item.id === this.formData.atlasNamethree || item.atlasName === this.formData.atlasNamethree) {
          data.atlasId = item.id
        }
      })
      if (this.formData.catalog) {
        data.catalog = 1
      } else {
        data.catalog = 0
      }
      data.catalogName = this.formData.catalogName
      data.fileName = this.formData.fileName
      data.id = this.formData.id
      editAtlaspic(data).then(res => {
        if (res.success === 1) {
          this.dialogShow = false
          this.$message.success('保存成功')
          this.$emit('refreshTable')
        }
      })
    },
    handleDetail(data) {
      this.tableData.splice(data, 1)
    },
    clearUpload() {
      this.tableData = []
    },
    searchPage() {
      searchAtlas().then(res => {
        if (res.success === 1) {
          this.atlasData = res.data.records
          const val = []
          for (let i = 0; i < res.data.records.length; i++) {
            val[i] = {}
            val[i].id = res.data.records[i].id
            val[i].atlasName = res.data.records[i].atlasName
            val[i].next = res.data.records[i].next
          }
          this.atlasoneList = val
          // 编辑时带出图册数据
          if (this.detailData) {
            // 一级图册
            this.atlasoneList.forEach(item => {
              if (this.detailData.firstAtlasId === item.id) {
                this.formData.atlasName = item.atlasName
                this.atlastwoList = item.next
              }
            })
          }
          // 二级图册
          if (this.detailData.secondAtlasId) {
            this.atlasoneList.forEach(item => {
              this.atlastwoList.forEach(itemtwo => {
                if (this.detailData.secondAtlasId === itemtwo.id) {
                  this.formData.atlasNametwo = itemtwo.atlasName
                  this.atlasthreeList = itemtwo.next
                }
              })
            })
          }
          // 三级图册
          if (this.detailData.atlasId) {
            this.atlasthreeList.forEach(itemthree => {
              if (this.detailData.atlasId === itemthree.id) {
                this.formData.atlasNamethree = itemthree.atlasName
              }
            })
          }
        }
      })
    },
    hadleSelectChange(val) {
      if (val !== this.detailData.firstAtlasId) {
        for (let i = 0; i < this.atlasData.length; i++) {
          if (val === this.atlasData[i].id) {
            this.atlastwoList = this.atlasData[i].next
            this.atlasthreeList = []
          }
        }
        this.formData.atlasNametwo = ''
        this.formData.atlasNamethree = ''
      }
      this.$forceUpdate()
    },
    hadleSelectChangetwo(val) {
      if (val !== this.detailData.secondAtlasId) {
        for (let i = 0; i < this.atlastwoList.length; i++) {
          if (val === this.atlastwoList[i].id) {
            this.atlasthreeList = this.atlastwoList[i].next
          }
        }
        this.formData.atlasNamethree = ''
      }

      this.$forceUpdate()
    },
    hadleSelectChangethree(val) {
      this.$forceUpdate()
    }
  }
}
</script>
<style lang='scss' scoped>
.el-col el-col-11{margin-bottom: 20px;}
.el-col el-col-11{margin-bottom: 20px;}
 .avatar-uploader .el-upload {
    border: 1px dashed #181717;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    border: 1px dashed #181717;
    border-radius: 6px;
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }
  .avatar {
    width: 120px;
    height: 120px;
    display: block;
  }
</style>
